import { fetchData } from '@/api';
import { defineStore } from 'pinia';

export const dataStore = defineStore('data', () => {
  // 获取所有数据
  const data = ref([]);
  const getAllData = async () => {
    const result = await fetchData();
    data.value = Object.entries(result).map((item) => {
      const data = Object.entries(item[1]).map((item) => {
        const value = Object.entries(item[1]).map((item) => {
          return {
            year: item[0],
            value: item[1]
          };
        });
        return {
          name: item[0],
          value
        };
      });
      return {
        province: item[0],
        data
      };
    });
    console.log('data: ', data.value);
  };

  // 人口数据
  const personData = computed(() => {
    const metaData = data.value;

    return metaData.map((provinceData) => {
      const provinceName = provinceData.province;
      const populationData = provinceData.data.find((item) => item.name === '年末常住人口').value;
      const urbanData = provinceData.data.find((item) => item.name === '城镇人口').value;
      const ruralData = provinceData.data.find((item) => item.name === '乡村人口').value;

      const totalPopulation = Number(populationData.find((entry) => entry.year === '2022').value);
      const urbanPopulation = Number(urbanData.find((entry) => entry.year === '2022').value);
      const ruralPopulation = Number(ruralData.find((entry) => entry.year === '2022').value);

      return {
        province: provinceName,
        totalPopulation: totalPopulation,
        urbanPopulation: urbanPopulation,
        ruralPopulation: ruralPopulation,
        total: urbanPopulation + ruralPopulation
      };
    });
  });

  // 获取地图数据：2022年，年末常住人口、城镇人口、乡村人口（万人）
  const mapData = computed(() => {
    const total = personData.value
      .map((item) => {
        return {
          name: item.province.replace(/省|市|自治区|回族|壮族|维吾尔/g, ''),
          value: item.total || 0
        };
      })
      .sort((a, b) => b.value - a.value);

    const tooltip = personData.value.map((item) => {
      return {
        name: item.province.replace(/省|市|自治区|回族|壮族|维吾尔/g, ''),
        value: [
          { name: '总人口', value: item.total },
          { name: '乡村人口', value: item.ruralPopulation },
          { name: '城镇人口', value: item.urbanPopulation },
          { name: '年末常住人口', value: item.totalPopulation }
        ]
      };
    });

    return {
      total,
      tooltip
    };
  });

  // 全国总人口
  const totalPerson = computed(() => {
    return mapData.value.total.reduce((acc, cur) => acc + cur.value, 0);
  });

  // 全国城镇人口
  const totalUrbanPerson = computed(() => {
    return mapData.value.tooltip.reduce((acc, cur) => {
      const item = cur.value.find((item) => item.name === '城镇人口');
      return acc + (item ? item.value : 0);
    }, 0);
  });

  // 全国农村人口
  const totalRuralPerson = computed(() => {
    return mapData.value.tooltip.reduce((acc, cur) => {
      const item = cur.value.find((item) => item.name === '乡村人口');
      return acc + (item ? item.value : 0);
    }, 0);
  });

  // 2018 - 2022年，农村人口、城镇人口人数变化
  const lineChartDataLeft = computed(() => {
    const result = {
      townPopulation: {},
      ruralPopulation: {}
    };

    // 遍历各个省份的数据
    data.value.forEach((province) => {
      province.data.forEach((item) => {
        if (item.name === '城镇人口') {
          item.value.forEach((yearData) => {
            const year = yearData.year;
            if (year >= 2018 && year <= 2022) {
              if (!result.townPopulation[year]) {
                result.townPopulation[year] = 0;
              }
              result.townPopulation[year] += parseInt(yearData.value);
            }
          });
        }

        if (item.name === '乡村人口') {
          item.value.forEach((yearData) => {
            const year = yearData.year;
            if (year >= 2018 && year <= 2022) {
              if (!result.ruralPopulation[year]) {
                result.ruralPopulation[year] = 0;
              }
              result.ruralPopulation[year] += parseInt(yearData.value);
            }
          });
        }
      });
    });

    return {
      category: Object.keys(result.townPopulation),
      data: [
        { name: '城镇人口', data: Object.values(result.townPopulation) },
        { name: '农村人口', data: Object.values(result.ruralPopulation) }
      ]
    };
  });

  // 2018 - 2022年，人口出生率、死亡率
  const lineChartDataRight = computed(() => {
    // 存储每个城市的总人口数、出生率和死亡率
    const cityData = {};

    // 遍历各个省份的数据
    data.value.forEach((province) => {
      province.data.forEach((item) => {
        // 处理城镇人口
        if (item.name === '城镇人口') {
          item.value.forEach((yearData) => {
            const year = yearData.year;
            const value = parseFloat(yearData.value);
            if (year === '2022') {
              if (!cityData[province.province]) {
                cityData[province.province] = { totalPopulation: 0, birthRate: 0, deathRate: 0 };
              }
              cityData[province.province].totalPopulation += value;
            }
          });
        }

        // 处理乡村人口
        if (item.name === '乡村人口') {
          item.value.forEach((yearData) => {
            const year = yearData.year;
            const value = parseFloat(yearData.value);
            if (year === '2022') {
              if (!cityData[province.province]) {
                cityData[province.province] = { totalPopulation: 0, birthRate: 0, deathRate: 0 };
              }
              cityData[province.province].totalPopulation += value;
            }
          });
        }

        // 处理人口出生率
        if (item.name === '人口出生率') {
          item.value.forEach((yearData) => {
            const year = yearData.year;
            const value = parseFloat(yearData.value);
            if (year === '2022') {
              if (!cityData[province.province]) {
                cityData[province.province] = { totalPopulation: 0, birthRate: 0, deathRate: 0 };
              }
              cityData[province.province].birthRate = value;
            }
          });
        }

        // 处理人口死亡率
        if (item.name === '人口死亡率') {
          item.value.forEach((yearData) => {
            const year = yearData.year;
            const value = parseFloat(yearData.value);
            if (year === '2022') {
              if (!cityData[province.province]) {
                cityData[province.province] = { totalPopulation: 0, birthRate: 0, deathRate: 0 };
              }
              cityData[province.province].deathRate = value;
            }
          });
        }
      });
    });

    // 将城市数据转换为数组并按总人口数排序
    const sortedCities = Object.entries(cityData)
      .sort((a, b) => b[1].totalPopulation - a[1].totalPopulation)
      .slice(0, 5);

    // 提取前五个城市的出生率和死亡率
    const topFiveCities = sortedCities.map(([province, data]) => ({
      province,
      totalPopulation: data.totalPopulation,
      birthRate: data.birthRate,
      deathRate: data.deathRate
    }));

    return {
      category: topFiveCities.map((item) => item.province),
      data: [
        { name: '出生率', data: topFiveCities.map((item) => item.birthRate) },
        { name: '死亡率', data: topFiveCities.map((item) => item.deathRate) }
      ]
    };
  });

  // 人口自然增长率 TOP5 省份
  const pieChardDataLeft = computed(() => {
    const growthRate2022 = {};

    // 遍历各个省份的数据
    data.value.forEach((province) => {
      province.data.forEach((item) => {
        // 查看人口自然增长率
        if (item.name === '人口自然增长率') {
          item.value.forEach((yearData) => {
            const year = yearData.year;
            const value = parseFloat(yearData.value);
            if (year === '2022') {
              growthRate2022[province.province] = value; // 存储2022年自然增长率
            }
          });
        }
      });
    });

    // 将省份数据转换为数组并按自然增长率排序
    const sortedProvinces = Object.entries(growthRate2022)
      .sort((a, b) => b[1] - a[1]) // 按自然增长率降序排序
      .slice(0, 8); // 获取前八个

    // 提取前五个省份的自然增长率
    const topFiveProvinces = sortedProvinces.map(([name, growthRate]) => ({
      name,
      value: growthRate
    }));

    return topFiveProvinces;
  });

  // 2020年各省男、女平均寿命
  const barChartDataLeft = computed(() => {
    const result = data.value.map((provinceData) => {
      const provinceName = provinceData.province;

      const maleLifespan = provinceData.data
        .find((item) => item.name === '男性平均预期寿命(岁)')
        .value.find((yearData) => yearData.year === '2020').value;
      const femaleLifespan = provinceData.data
        .find((item) => item.name === '女性平均预期寿命(岁)')
        .value.find((yearData) => yearData.year === '2020').value;

      return {
        province: provinceName,
        maleLifespan: maleLifespan,
        femaleLifespan: femaleLifespan
      };
    });

    return {
      category: result.map((item) => item.province),
      data: [
        {
          name: '男性平均寿命',
          value: result.map((item) => Number(item.maleLifespan))
        },
        {
          name: '女性平均寿命',
          value: result.map((item) => Number(item.femaleLifespan))
        }
      ]
    };
  });

  // 2020年各省男、女平均寿命 TOP5
  const barChartDataRight = computed(() => {
    const maleLifespans = data.value.map((provinceData) => {
      const provinceName = provinceData.province;

      const maleLifespan = provinceData.data
        .find((item) => item.name === '男性平均预期寿命(岁)')
        .value.find((yearData) => yearData.year === '2020').value;
      const femaleLifespan = provinceData.data
        .find((item) => item.name === '女性平均预期寿命(岁)')
        .value.find((yearData) => yearData.year === '2020').value;

      return {
        province: provinceName,
        maleLifespan: parseFloat(maleLifespan),
        femaleLifespan: parseFloat(femaleLifespan)
      };
    });

    // 按男性平均寿命降序排序
    maleLifespans.sort((a, b) => b.maleLifespan - a.maleLifespan);

    // 获取前五个
    const topFive = maleLifespans.slice(0, 5);

    return {
      category: topFive.map((item) => item.province),
      data: [
        {
          name: '男性平均寿命',
          value: topFive.map((item) => Number(item.maleLifespan))
        },
        {
          name: '女性平均寿命',
          value: topFive.map((item) => Number(item.femaleLifespan))
        }
      ]
    };
  });

  // 2020年平均寿命 TOP8
  const pieChardDataRight = computed(() => {
    const lifespans = data.value.map((provinceData) => {
      const provinceName = provinceData.province;

      const averageLifespan = provinceData.data
        .find((item) => item.name === '平均预期寿命(岁)')
        .value.find((yearData) => yearData.year === '2020').value;

      return {
        province: provinceName,
        averageLifespan: parseFloat(averageLifespan)
      };
    });

    // 按平均寿命降序排序
    lifespans.sort((a, b) => b.averageLifespan - a.averageLifespan);

    // 获取前八个
    const topEight = lifespans.slice(0, 8);

    return topEight.map((item) => {
      return {
        name: item.province,
        value: item.averageLifespan
      };
    });
  });

  // 初始化 Store
  const init = async () => {
    await getAllData();
  };

  return {
    init,
    mapData,
    personData,
    totalPerson,
    pieChardDataLeft,
    barChartDataLeft,
    totalUrbanPerson,
    totalRuralPerson,
    pieChardDataRight,
    lineChartDataLeft,
    barChartDataRight,
    lineChartDataRight
  };
});
